// Copyright 2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Gunnar Ritter

#import "config/applemail_plist.h"

#import <Foundation/NSAutoreleasePool.h>
#import <AppKit/NSApplication.h>
#import <Foundation/NSPropertyList.h>
#import <Foundation/NSData.h>
#import <Foundation/NSArray.h>
#import <Foundation/NSString.h>
#import <Foundation/NSException.h>

AppleMailPlist::AppleMailPlist()
    : error_message_(NULL) {
}

bool AppleMailPlist::Read(QString path) {
  bool succeeded = false;
  NSApplicationLoad();
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  const char *cpath = path.toUtf8().data();
  NSString *nspath = [NSString stringWithUTF8String:cpath];
  NSData *data = [NSData dataWithContentsOfFile:nspath];
  if (data) {
    NSString *error = NULL;
    NSPropertyListFormat format;
    NSDictionary *dict = [NSPropertyListSerialization
      propertyListFromData:data
          mutabilityOption:NSPropertyListImmutable
                    format:&format
          errorDescription:&error];
    if (!error) {
      @try {
        accounts_version_ = [[dict objectForKey: @"AccountsVersion"] intValue];
        SetDeliveryAccountsFromDict(dict);
        SetMailAccountsFromDict(dict);
        succeeded = true;
      }
      @catch (NSException *e) {
        error_message_ = "Invalid Plist structure";
      }
    } else {
      error_message_ = [error UTF8String];
      [error release];
    }
  }
  [pool release];
  return succeeded;
}

void AppleMailPlist::SetDeliveryAccountsFromDict(NSDictionary *dict) {
  NSArray *accounts = [dict objectForKey: @"DeliveryAccounts"];
  int naccounts = [accounts count];
  for (int i = 0; i < naccounts; ++i) {
    NSDictionary *a_dict = [accounts objectAtIndex:i];
    struct DeliveryAccount a_struct;
    a_struct.AccountType = [[a_dict objectForKey: @"AccountType"] UTF8String];
    a_struct.Hostname = [[a_dict objectForKey: @"Hostname"] UTF8String];
    a_struct.SSLEnabled = [[a_dict objectForKey: @"SSLEnabled"] boolValue] ?
      true : false;
    a_struct.SecurityLayerType =
      [[a_dict objectForKey: @"SecurityLayerType"] intValue];
    a_struct.ShouldUseAuthentication =
      [[a_dict objectForKey: @"ShouldUseAuthentication"] boolValue] ?
        true : false;
    a_struct.Username = [[a_dict objectForKey: @"Username"] UTF8String];
    delivery_accounts_.append(a_struct);
  }
}

void AppleMailPlist::SetMailAccountsFromDict(NSDictionary *dict) {
  NSArray *accounts = [dict objectForKey: @"MailAccounts"];
  int naccounts = [accounts count];
  for (int i = 0; i < naccounts; ++i) {
    NSDictionary *a_dict = [accounts objectAtIndex:i];
    struct MailAccount a_struct;
    a_struct.AccountName = [[a_dict objectForKey: @"AccountName"] UTF8String];
    a_struct.AccountType = [[a_dict objectForKey: @"AccountType"] UTF8String];
    a_struct.DeleteMessagesOnServerInterval =
      [[a_dict objectForKey: @"DeleteMessagesOnServerInterval"] intValue];
    a_struct.DeletionPolicy =
      [[a_dict objectForKey: @"DeletionPolicy"] UTF8String];
    NSArray *addresses = [a_dict objectForKey: @"EmailAddresses"];
    int naddresses = [addresses count];
    if (naddresses > 0) {
      for (int j = 0; j < naddresses; ++j) {
        NSString *address = [addresses objectAtIndex:j];
        a_struct.EmailAddresses.append([address UTF8String]);
      }
    } else {
      a_struct.EmailAddresses.append("");
    }
    a_struct.FullUserName = [[a_dict objectForKey: @"FullUserName"] UTF8String];
    a_struct.Hostname = [[a_dict objectForKey: @"Hostname"] UTF8String];
    a_struct.PortNumber = [[a_dict objectForKey: @"PortNumber"] intValue];
    a_struct.SMTPIdentifier =
      [[a_dict objectForKey: @"SMTPIdentifier"] UTF8String];
    a_struct.SSLEnabled = [[a_dict objectForKey: @"SSLEnabled"] boolValue] ?
      true : false;
    a_struct.SecurityLayerType =
      [[a_dict objectForKey: @"SecurityLayerType"] intValue];
    a_struct.Username = [[a_dict objectForKey: @"Username"] UTF8String];
    mail_accounts_.append(a_struct);
  }
}
